const cloud = require('wx-server-sdk');
cloud.init({
	env: cloud.DYNAMIC_CURRENT_ENV
});

const TcbRouter = require('tcb-router');
const db = cloud.database()
const _ = db.command;
const crypto = require('crypto');

exports.main = async (event, context) => {
	const app = new TcbRouter({ event });
	const { orderId, payOrderInfo } = event
	let { OPENID, APPID } = cloud.getWXContext()

	// 获取支付参数
	app.router('getPaymentParams', async (ctx, next) => {
		try {
			const orderInfo = await getOrderInfo(OPENID, orderId); // 获取订单信息
			if (!orderInfo) {
				ctx.body = { code: -1, message: 'Order not found' };
				return;
			}
			
			const payment = await unifiedOrder(orderInfo);
			//新建一条未支付的订单
			const payOrderExist = await db.collection('pay_order').where({out_trade_no: orderInfo.out_trade_no}).get()
			if (payOrderExist.data.length > 0) {
				 await db.collection('pay_order').doc(payOrderExist.data[0]._id).update({
					 data: {
						 create_time: new Date()
					 }
				})
			}else {
				await db.collection('pay_order').add({
					data: {
						...orderInfo,
						create_time: new Date()
					}
				})
			}
			ctx.body = { code: 0, message: "success", data: payment };
		} catch (error) {
			console.error(error);
			ctx.body = { code: -1, message: 'Failed to get payment params' };
		}
	});
	
	app.router('myChargeRecord', async(ctx, next) => {
		try {
			const getData = await db.collection('pay_order').where({open_id: OPENID}).get()
			console.log("调用myChargeRecord", getData)
			if (getData.data.length > 0) {
				ctx.body = {code: 200, msg: '成功', data: getData.data}
			}else {
				ctx.body = {code: 200, msg: '没有数据', data: {}}
			}
		}catch(error) {
			ctx.body = {code: 301, msg: '查询异常', data: {}}
		}
	})
	return app.serve();
};

// 模拟获取订单信息的方法
async function getOrderInfo(openid, orderId) {
	try {
		const getData = await db.collection('order').doc(orderId).get()
		const order = getData.data
		const orderInfo = {
			out_trade_no: generateOrderNo(openid, orderId),
			// total:  order.price * 100,  //单位分
			total: 1,
			remark: '宠症智识扫描次数',
			open_id: openid,
			order_id: orderId,
			integral: order.integral
		}
		return orderInfo
	}catch(error) {
		return false
	}
}

// 统一下单接口
async function unifiedOrder(orderInfo) {
	const res = await cloud.cloudPay.unifiedOrder({
		body: orderInfo.remark,
		outTradeNo: orderInfo.out_trade_no,
		spbillCreateIp: '123.12.12.123', // 用户端实际IP地址
		subMchId: '1715430025', // 子商户号（如果有）
		totalFee: orderInfo.total,
		envId: 'cloud1-2g67qrjjca1d7b80', // 云函数环境名称
		functionName: 'monitor' // 支付结果通知回调云函数名
	});
	return res.payment;
}

// 解析XML数据
async function parseXml(xmlString) {
	const parser = new xml2js.Parser({ explicitArray: false, trim: true });
	return await parser.parseStringPromise(xmlString);
}

function generateOrderNo(userId, productId) {
    const timestamp = Math.floor(Date.now() / 1000);
    const randomNumber = crypto.randomInt(1000, 9999);
    let orderNo = `${randomNumber}_${productId}_${timestamp}_${userId}`;

    if (orderNo.length > 32) {
        orderNo = orderNo.substring(0, 32);
    }
    return orderNo;
}